package com.pan.admin.module.visualizer.service.impl;

import com.gitee.apanlh.util.base.BigDecimalUtils;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.enums.Sort;
import com.pan.admin.cache.FormLocalCache;
import com.pan.admin.generator.constant.ApiGenFieldEnum;
import com.pan.admin.module.datareport.entity.StartTimeAndEndTime;
import com.pan.admin.module.form.entity.FormPO;
import com.pan.admin.module.visualizer.dao.LoanChannelVisualizerDao;
import com.pan.admin.module.visualizer.entity.po.ChannelVisualizerFormFieldPO;
import com.pan.admin.module.visualizer.entity.vo.LoanChannelVisualizerVO;
import com.pan.admin.module.visualizer.entity.vo.LoanMarketDetailVO;
import com.pan.admin.module.visualizer.service.LoanChannelVisualizerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * H5/APP渠道
 *
 * @author caoxin
 */
@Service
public class LoanChannelVisualizerServiceImpl implements LoanChannelVisualizerService {

    @Autowired
    private LoanChannelVisualizerDao loanChannelVisualizerDao;
    @Autowired
    private FormLocalCache formLocalCache;

    @Override
    @Transactional(readOnly = true)
    public List<LoanChannelVisualizerVO> list(StartTimeAndEndTime startTimeAndEndTime, String name) {
        String displayDateTime;

        //  拼接时间
        if (startTimeAndEndTime.ifNull()) {
            displayDateTime = "当日数据截止至" + LocalDate.now();
        } else {
            displayDateTime = startTimeAndEndTime.getStartTime() + "至" + startTimeAndEndTime.getEndTime();
        }

        startTimeAndEndTime.ifNullGen1();

        List<LoanChannelVisualizerVO> loanChannelList = loanChannelVisualizerDao.listLoanChannel(name);
        List<LoanChannelVisualizerVO> uvList = loanChannelVisualizerDao.listUv(startTimeAndEndTime);
        List<LoanChannelVisualizerVO> pvList = loanChannelVisualizerDao.listPv(startTimeAndEndTime);
        List<LoanChannelVisualizerVO> registerList = loanChannelVisualizerDao.listRegister(startTimeAndEndTime);
        List<LoanChannelVisualizerVO> formList = loanChannelVisualizerDao.listForm(startTimeAndEndTime);
        List<LoanChannelVisualizerVO> oldUserList = loanChannelVisualizerDao.listOldUser(startTimeAndEndTime);
        List<LoanChannelVisualizerVO> loanMarketList = loanChannelVisualizerDao.listLoanMarket(startTimeAndEndTime);
        List<LoanChannelVisualizerVO> formRevenueList = loanChannelVisualizerDao.listFormRevenue(startTimeAndEndTime);
        List<LoanChannelVisualizerVO> loanMarketRevenueList = loanChannelVisualizerDao.listLoanMarketRevenue(startTimeAndEndTime);

        //  获取芝麻分资质
        List<FormPO> sesameCreditMapping = formLocalCache.getByMappingName(ApiGenFieldEnum.SESAME_CREDIT.getFieldName());
        List<ChannelVisualizerFormFieldPO> listSesameCreditForm = loanChannelVisualizerDao.listByFormFieldById(sesameCreditMapping.getFirst().getFormFieldId(), startTimeAndEndTime);
        Map<Long, List<ChannelVisualizerFormFieldPO>> listSesameCreditFormGroup = CollUtils.groupBy(listSesameCreditForm, t -> t.getLoanChannelId());

        loanChannelList.forEach(loanChannel -> {
            uvList.forEach(uv -> {
                if (Objects.equals(loanChannel.getId(), uv.getId())) {
                    loanChannel.setUv(uv.getUv());
                }
            });
            pvList.forEach(pv -> {
                if (Objects.equals(loanChannel.getId(), pv.getId())) {
                    loanChannel.setPv(pv.getPv());
                }
            });
            registerList.forEach(register -> {
                if (Objects.equals(loanChannel.getId(), register.getId())) {
                    loanChannel.setRegister(register.getRegister());
                }
            });
            formList.forEach(form -> {
                if (Objects.equals(loanChannel.getId(), form.getId())) {
                    loanChannel.setForm(form.getForm());
                }
            });
            oldUserList.forEach(oldUser -> {
                if (Objects.equals(loanChannel.getId(), oldUser.getId())) {
                    loanChannel.setOldUser(oldUser.getOldUser());
                }
            });

            //  芝麻分资质
            List<ChannelVisualizerFormFieldPO> sesameCreditFormGroup = listSesameCreditFormGroup.get(loanChannel.getId());

            loanMarketList.forEach(loanMarket -> {
                if (Objects.equals(loanChannel.getId(), loanMarket.getId())) {
                    loanChannel.setLoanMarket(loanMarket.getLoanMarket());
                }
            });
            formRevenueList.forEach(formRevenue -> {
                if (Objects.equals(loanChannel.getId(), formRevenue.getId())) {
                    loanChannel.setFormRevenue(formRevenue.getFormRevenue());
                }
            });
            loanMarketRevenueList.forEach(loanMarketRevenue -> {
                if (Objects.equals(loanChannel.getId(), loanMarketRevenue.getId())) {
                    loanChannel.setLoanMarketRevenue(loanMarketRevenue.getLoanMarketRevenue());
                }
            });
            // 总收益。总收益 = 表单收益 + 贷超收益
            BigDecimal totalRevenue = BigDecimalUtils.plus(loanChannel.getFormRevenue(), loanChannel.getLoanMarketRevenue());
            // 总成本。结算方式 是 UV 的时候： 总成本 = uv * 结算价格, 注册 是 结算方式 的时候： 总成本 = 结算价格 * 注册
            BigDecimal totalCost = ChooseEq.create()
                    .when(loanChannel.getPriceType(), "0", BigDecimalUtils.multiply(loanChannel.getPrice(), loanChannel.getUv()))
                    .when(loanChannel.getPriceType(), "1", BigDecimalUtils.multiply(loanChannel.getPrice(), loanChannel.getRegister()))
                    .end(BigDecimal.ZERO);
            // 总利润。总利润 = 总收益 - 总成本
            BigDecimal totalProfit = totalRevenue.subtract(totalCost);
            loanChannel.setTotalRevenue(totalRevenue);
            loanChannel.setTotalCost(totalCost);
            loanChannel.setTotalProfit(totalProfit );
            loanChannel.setDateTime(displayDateTime);
        });

        //  UV排序
        CollUtils.sortStr(loanChannelList, "uv", Sort.DESC);
        return loanChannelList;
    }

    @Override
    public List<LoanMarketDetailVO> listLoanMarketDetail(StartTimeAndEndTime startTimeAndEndTime, Long id) {
        String displayDateTime;

        //  拼接时间
        if (startTimeAndEndTime.ifNull()) {
            displayDateTime = "当日数据截止至" + LocalDate.now();
        } else {
            displayDateTime = startTimeAndEndTime.getStartTime() + "至" + startTimeAndEndTime.getEndTime();
        }

        startTimeAndEndTime.ifNullGen1();

        List<LoanMarketDetailVO> list = loanChannelVisualizerDao.listLoanMarketDetail(startTimeAndEndTime, id);
        list.forEach(item -> item.setDateTime(displayDateTime));
        return list;
    }

}
